package com.gitee.shop.controller;

import com.gitee.shop.domain.User;
import com.gitee.shop.service.UserService;
import com.ramostear.captcha.HappyCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {

    //注入service
    @Autowired
    private UserService userService;

    //login
    @RequestMapping("/login")
    public String loginUser(String username , String password ,String captcha , HttpServletRequest request , Model model){
        //校验验证码
        System.out.println("username="+username +"password = "+password +"captcha = "+captcha);
        boolean rs = HappyCaptcha.verification(request,captcha,true);
        //验证码输入不正确
        if(!rs){
            //提示错误
            model.addAttribute("error", "请输入正确的验证码");
            //返回登陆页面
            return "login";
        }
        User user = userService.loginUser(username,password);
        if (user != null){
            request.getSession().setAttribute("user",user);
            //重定向到首页
            return "redirect:/";
        }else {
            model.addAttribute("error","用户名或密码错误");
            //返回登陆页面
            return "login";
        }


    }

    //退出
    @RequestMapping("/quit")
    public String quit(HttpSession session){
        session.removeAttribute("user");
        return "login";
    }
}
